package com.dek.ioc.utils;

import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
import org.junit.Test;

import com.dek.ioc.config.Bean;
import com.dek.ioc.config.Property;

public class ConfigManager {
	
	/**
	 * 1.  创建解析器
	 * 2.  加载配置文件 
	 * 3.   定义xpath表达式，取出所有bean元素
	 *  4. 对bean元素遍历
	 *  5. 对property进行遍历
	 * @return
	 */
	public static Map<String, Bean> getConfig(String path) {
		
		//1 创建解析器
		SAXReader reader = new SAXReader();
		//2
		InputStream is = ConfigManager.class.getResourceAsStream(path);
		Document document = null;
		try {
			document = reader.read(is);
		} catch (DocumentException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			throw new RuntimeException("xml 配置错误");
		}
		
		String xpath = "//bean";
		
		Map<String, Bean> map = new HashMap<>();
		
		List<Element> list = document.selectNodes(xpath);
		if (list != null) {
			for(Element e : list) {
				Bean bean = new Bean();
				bean.setName(e.attributeValue("name"));
				bean.setClazz(e.attributeValue("class"));
				if (e.attributeValue("scope") != null) {
					bean.setScope(e.attributeValue("scope"));
				}
				
				List<Element> properties = e.elements("property");
				List<Property> p = new ArrayList<>();
				if (properties != null) {
					for(Element pe : properties) {
						Property property = new Property();
						property.setName(pe.attributeValue("name"));
						property.setRef(pe.attributeValue("ref"));
						property.setValue(pe.attributeValue("value"));
						p.add(property);
					}
				}
				bean.setProperties(p);
				map.put(bean.getName(), bean);
			}
		}
		return map;
	}
	
	
	@Test
	public void test() {
		Map<String, Bean> config = ConfigManager.getConfig("/spring-context.xml");
		System.out.println(config);
	}
	
	
}
